package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.DimUtil;
import com.atguigu.gmall.realtime.utils.PhoenixUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.util.Collection;
import java.util.Set;

/**
 * @author Felix
 * @date 2023/4/14
 * 将维度流数据写到Phoenix表中
 */
public class DimSinkFunction implements SinkFunction<JSONObject> {
    @Override
    public void invoke(JSONObject jsonObj, Context context) throws Exception {
        //jsonObj: {"tm_name":"Redmi5","sink_table":"dim_base_trademark","id":1}
        // upsert into 表名 (a,b,c) values('aa','bb','cc')
        //获取输出的目的地表名
        String tableName = jsonObj.getString("sink_table");
        // {"tm_name":"Redmi5","id":1}
        jsonObj.remove("sink_table");

        String type = jsonObj.getString("type");
        jsonObj.remove("type");

        //获取json对象中所有的key
        Set<String> keys = jsonObj.keySet();
        //获取json对象中所有的value
        Collection<Object> values = jsonObj.values();

        //拼接upsert语句
        String upsertSql = "upsert into " + GmallConfig.PHOENIX_SCHEMA + "." + tableName
            + " (" + StringUtils.join(keys, ",") + ") " +
            "values('" + StringUtils.join(values, "','") + "')";

        System.out.println("向Phoenix表中插入数据的sql:" + upsertSql);

        PhoenixUtil.executeSql(upsertSql);
        //如果维度数据发生了变化，将Redis中缓存的数据清除掉
        if("update".equals(type)){
            DimUtil.delCached(tableName,jsonObj.getString("id"));
        }

    }
}
